﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Tools.Net
{
    public class SocketOpera
    {
        public Socket socket { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        public SocketOpera(string host, int port)
        {
            var ipe = new IPEndPoint(IPAddress.Parse(host), port);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(ipe);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sendStr"></param>
        /// <returns></returns>
        public int Send(string sendStr)
        {
            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            return socket.Send(bs, bs.Length, 0);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string Receive(Encoding en = null)
        {
            en = en ?? Encoding.GetEncoding("gbk");
            string recvStr = "";
            byte[] recvBytes = new byte[1024];
            int bytes;
            bytes = socket.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
            recvStr += en.GetString(recvBytes, 0, bytes);
            return recvStr;
        }

        public string SendReceive(string sendStr)
        {
            int r = Send(sendStr);
            return Receive();
        }

    }
}
